﻿using BusinessLayer;
using BusinessLayer.DatabaseEntities;
using BusinessLayer.VDataEntities;
using CustomerServiceCenter.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Security;

namespace CustomerServiceCenter.Auth
{
    public static class Authenticate
    {
        static Client client = null;

        public static VPromoter CheckWeiXinUser(long clientID)
        {
            VPromoter promoter = null;

            string userID = string.Empty;

            HttpCookie aCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName + "userid"];
            HttpCookie client_Cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName + "clientid"];
            long clientid=0;
            if (client_Cookie != null)
            {
                long.TryParse(FormsAuthentication.Decrypt(client_Cookie.Value).UserData.ToString(), out clientid);
                LogHelper.Info("验证ClientID，从Cookie" + clientid);
            }
            

            if (aCookie == null||client_Cookie == null||clientID!=clientid)
            {
                client = ClientBusiness.GetClient(clientID);
                //判断guuid是否存在数据库中
                if (client == null)
                {
                    HttpContext.Current.Response.Redirect("~Error/ErrorURL");
                }
                //LogHelper.Info("数据库判断GUUID,获取到的cropID是："+client.CropID);
                //LogHelper.Info("code" + HttpContext.Current.Request.QueryString["code"]);

                //LogHelper.Info("cookies is null,begin to authenticate");
                //获取token
                WeChatHelper wechatHelp = new WeChatHelper();
                string token = wechatHelp.GetToken(client);
                //获取code的URL
                string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect",
   client.CropID, ConfigurationManager.AppSettings["WeixinBaseUrl"].ToString() + "?id=" + client.Guuid, "snsapi_base", "Test");


                LogHelper.Info("获取到的token是：\r\n" + token + "\r\n");
                //如果有code
#region code
                if (HttpContext.Current.Request.QueryString["code"] != null)
                {
                    //获取用户信息
                    string userurl = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", token, HttpContext.Current.Request.QueryString["code"]);
                    HttpWebRequest hwr = WebRequest.Create(userurl) as HttpWebRequest;
                    hwr.Method = "POST";
                    hwr.ContentType = "application/x-www-form-urlencoded";
                    var result = hwr.GetResponse() as HttpWebResponse;
                    StreamReader reader = new StreamReader(result.GetResponseStream(), Encoding.UTF8);
                    string content = reader.ReadToEnd();
                    reader.Close();
                    reader.Dispose();
                    var obj = JsonConvert.DeserializeObject(content) as JObject;
                    LogHelper.Info("获取用户信息:"+content);
                    if (obj["UserId"] == null)
                    {
                        //表示非企业成员
                        return promoter;
                    }
                    else
                    {
                        //如果获取到企业用户
                        LogHelper.Info("Get UserInfo from wechat:" + obj.ToString());
                        //验证在不在项目应用中
                        VPromoter validatePromoter = PromoterBusiness.ValidatePromoter(obj["UserId"].ToString(), client.ID);
                        LogHelper.Info("ValidatePromoter:" + validatePromoter);
                        if (validatePromoter == null)
                        {

                            VEndUser enduser = new VEndUser
                            {
                                Name = obj["UserId"].ToString(),
                                ClientID = client.ID
                            };
                            LogHelper.Info("do add:" + enduser.Name+"----"+enduser.ClientID);
                            PromoterBusiness.AddPromoter(enduser);
                            LogHelper.Info("AddUser:\r\nName:"+enduser.Name+"ClientID:"+enduser.ClientID);
                        }
                        validatePromoter = PromoterBusiness.ValidatePromoter(obj["UserId"].ToString(), client.ID);
                        #region 添加Cookie
                        //添加cookie
                        FormsAuthenticationTicket ticket_user = new FormsAuthenticationTicket(1, FormsAuthentication.FormsCookieName + "userid", DateTime.Now,
                            DateTime.Now.AddMinutes(5), true, obj["UserId"].ToString());
                        string userinfoticket = FormsAuthentication.Encrypt(ticket_user);
                        //添加userid到cookie
                        var cookie_user = new HttpCookie(FormsAuthentication.FormsCookieName + "userid", userinfoticket);
                        cookie_user.HttpOnly = true;
                        cookie_user.Expires = DateTime.Now.AddHours(20);
                        HttpContext.Current.Response.Cookies.Add(cookie_user);

                        //添加cookie
                        FormsAuthenticationTicket ticket_client = new FormsAuthenticationTicket(1, FormsAuthentication.FormsCookieName + "clientid", DateTime.Now,
                            DateTime.Now.AddMinutes(5), true, client.ID.ToString());
                        string clientinfoticket = FormsAuthentication.Encrypt(ticket_client);
                        //添加clientid到cookie
                        var cookie_client = new HttpCookie(FormsAuthentication.FormsCookieName + "clientid", clientinfoticket);
                        cookie_client.HttpOnly = true;
                        cookie_client.Expires = DateTime.Now.AddHours(20);
                        HttpContext.Current.Response.Cookies.Add(cookie_client);
#endregion 添加Cookie结束
                        //userID = obj["UserId"].ToString();
                        promoter = validatePromoter;
                    }
                }

                else
                {
                    HttpContext.Current.Response.Redirect(url);
                }
#endregion
            }

            else
            {
               
                if (aCookie != null && !string.IsNullOrEmpty(aCookie.Value)&&client_Cookie != null && !string.IsNullOrEmpty(client_Cookie.Value))
                {
                    try
                    {
                        FormsAuthenticationTicket tit = FormsAuthentication.Decrypt(aCookie.Value);
                        FormsAuthenticationTicket tit_client = FormsAuthentication.Decrypt(client_Cookie.Value);
                        userID = tit.UserData;
                        
                        long.TryParse(tit_client.UserData.ToString(), out clientid);
                        promoter = new VPromoter
                        {
                            ChineseName = userID,
                            ClientID = clientid
                        };
                        LogHelper.Info("Get User from cookie:" + promoter.ToString());
                    }
                    catch
                    {
                        userID = string.Empty;
                    }
                }
                return promoter;
            }
            return promoter;
        }
    }

}